package main

import (
	"common/perf"
	"common/process"
	"flag"
	"iot-bridge/iot_cmd_up/ping/conf"
	"iot-bridge/iot_cmd_up/ping/controller"
	"iot-bridge/iot_cmd_up/ping/dao"
	"iot-bridge/iot_cmd_up/ping/service"
	"os"
	"os/signal"
	"runtime"
	"syscall"

	log "common/log4go.v1"
)

var (
	confPath string
)

const (
	version = "1.0"
)

func init() {
	flag.StringVar(&confPath, "conf", "./conf_ts.ini", " set config file path")
}

func main() {

	flag.Parse()
	if err := conf.Init(confPath); err != nil {
		log.Error("conf.Init(\"%s\") error(%v)", confPath, err)
		panic(err)
	}

	runtime.GOMAXPROCS(conf.Conf.Base.MaxProc)
	//init log
	log.LoadConfiguration(conf.Conf.Base.LogPath)
	defer log.Close()

	//init dao
	if err := dao.Init(); err != nil {
		log.Error("dao.Init() error(%v)", err)
		panic(err)
	}
	defer dao.Close()

	// init pprof
	if err := perf.Init(conf.Conf.Base.PprofAddr); err != nil {
		log.Error("perf.Init() error(%v)", err)
		panic(err)
	}
	defer perf.Close()

	// process init
	if err := process.Init(conf.Conf.Base.PidFile); err != nil {
		log.Error("process.Init(%s) error(%v)", conf.Conf.Base.PidFile, err)
		panic(err)
	}

	// init service
	if err := service.Init(); err != nil {
		log.Error("service.Init() error(%v)", err)
		panic(err)
	}
	defer service.Close()

	factory := controller.NewFactory(conf.Conf.Kafka)
	if err := factory.CreateWorks(conf.Conf.Factory.PartionCount / conf.Conf.Factory.MachineCount); err != nil {
		log.Error("factory.CreateWorks(%d) error(%d)", conf.Conf.Factory.PartionCount/conf.Conf.Factory.MachineCount, err)
		return
	}
	go factory.Begin()
	defer factory.Close()

	log.Info("iot_cmd_up_data_change [version: %s] start", version)

	// init signal
	c := make(chan os.Signal, 1)
	signal.Notify(c, syscall.SIGHUP, syscall.SIGQUIT, syscall.SIGTERM, syscall.SIGINT, syscall.SIGSTOP)
	for {
		s := <-c
		log.Info("iot_cmd_up_data_change get a signal %s", s.String())
		switch s {
		case syscall.SIGQUIT, syscall.SIGTERM, syscall.SIGSTOP, syscall.SIGINT:
			log.Info("iot_cmd_up_data_change [version: %s] exit", version)
			return
		case syscall.SIGHUP:
		// TODO reload
		default:
			return
		}
	}
}
